//
//  ConnectTableViewController.m
//  Wifi
//
//  Created by srulos on 2017/6/9.
//  Copyright © 2017年 srulos. All rights reserved.
//

#import "ConnectTableViewController.h"
#import "WifiHeader.h"
#import "ConnectTitleTableViewCell.h"
#import "ConnectedTableViewCell.h"
#import "ConnectSelectTableViewCell.h"
#import "LoginViewController.h"

@interface ConnectTableViewController ()<UIAlertViewDelegate>
{
    UIAlertView * m_addWifiAlertView;
    NSMutableDictionary * m_dicLocalWifi;
}
@end

@implementation ConnectTableViewController

- (void)viewWillAppear:(BOOL)animated{
    [self.navigationController.navigationBar setHidden:NO];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"Wi-Fi Memorandum";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(onAddWifiCB:)];
    
    
    SHOW_HUD(K_NSLOCAL(@"loading"));
    
    dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC);
    dispatch_after(time, dispatch_get_main_queue(), ^{
        HIDE_HUD;
        [self loadLocalWifi];
        [self.tableView reloadData];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        if (IS_CHINESE) {
            if ([Util isWIFIConnection]) {//是否已连接Wifi
                return 2;
            }
            else{
                return 1;
            }
        }
        else{
            return 0;
        }
    }
    else{//加载列表
        return m_dicLocalWifi.count;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString * cellIdentifier = [NSString stringWithFormat:@"%ld-%ld",indexPath.section,indexPath.row];
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                cell = VIEW_INIT_NIB(ConnectTitleTableViewCell);
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            else if(indexPath.row == 1){
                cell = VIEW_INIT_NIB(ConnectedTableViewCell);
            }
        }
        else if(indexPath.section == 1){
            cell = VIEW_INIT_NIB(ConnectSelectTableViewCell);
        }
    }
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            ConnectTitleTableViewCell * connectTitleTableViewCell = (ConnectTitleTableViewCell*)cell;
            if ([Util isWIFIConnection]) {
                [connectTitleTableViewCell.m_switchIsConnectedWiFi setOn:YES];
            }
            else{
                [connectTitleTableViewCell.m_switchIsConnectedWiFi setOn:NO];
            }
        }
        else if(indexPath.row == 1){
            ConnectedTableViewCell * connectedTableViewCell = (ConnectedTableViewCell*)cell;
            NSString * wifiName = [Util getCurrentConnectedWifiName];
            connectedTableViewCell.m_labelCurrentConnectedWifiName.text = wifiName.length > 0 ? wifiName : @"Unkown";
        }
    }
    else if(indexPath.section == 1){
        ConnectSelectTableViewCell * connectSelectTableViewCell = (ConnectSelectTableViewCell*)cell;
        
        NSArray * keys = [m_dicLocalWifi allKeys];
        NSString * key = [keys objectAtIndex:indexPath.row];
        
        connectSelectTableViewCell.m_labelWiFiName.text = key;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 10.0f;
    }
    else{
        return 20.0f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 20.0f;
    }
    else{
        return 0.01f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.0f;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return UITableViewCellEditingStyleDelete;
    }
    
    return UITableViewCellEditingStyleNone;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return YES;
    }
    return NO;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return K_NSLOCAL(@"Delete");
}

- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return K_NSLOCAL(@"SelectNetwork");
    }
    return nil;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            ALERT_VIEW(nil,K_NSLOCAL(@"NetWorkNormal"));
        }
    }
    else if(indexPath.section == 1){
        NSArray * keys = [m_dicLocalWifi allKeys];
        NSString * key = [keys objectAtIndex:indexPath.row];
        
        NSString * password = [m_dicLocalWifi objectForKey:key];
        
        UIPasteboard * pasteboard = [UIPasteboard generalPasteboard];
        
        pasteboard.string = password;
        
        NSString * message = [NSString stringWithFormat:@"%@【%@】%@",K_NSLOCAL(@"PasswordIs"),password,K_NSLOCAL(@"CopyToBoard")];
        ALERT_VIEW(nil,message);
    }
}

#pragma mark - add wifi
- (void)onAddWifiCB:(id)sender
{
    if (![MPWeChat stander].m_isLogin) {
        [self login];
        return;
    }
    
    if (m_addWifiAlertView == nil) {
        m_addWifiAlertView = [[UIAlertView alloc] initWithTitle:K_NSLOCAL(@"AddHot") message:nil delegate:self cancelButtonTitle:K_NSLOCAL(@"Cancel") otherButtonTitles:K_NSLOCAL(@"OK"), nil];
        [m_addWifiAlertView setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
    }
    
    UITextField *nameField = [m_addWifiAlertView textFieldAtIndex:0];
    nameField.placeholder = K_NSLOCAL(@"WifiName");
    nameField.text = @"";
    
    UITextField * passwordField = [m_addWifiAlertView textFieldAtIndex:1];
    [passwordField setSecureTextEntry:NO];
    passwordField.placeholder = K_NSLOCAL(@"WifiPassword");
    passwordField.text = @"";
    
    [m_addWifiAlertView show];
}

-(void)login
{
    UIAlertController *alertController=[UIAlertController alertControllerWithTitle:NSLocalizedString(@"PleaseLogin", nil) message:NSLocalizedString(@"NeedLogin", nil) preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction * actionOne =[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil)
                                                        style:UIAlertActionStyleCancel
                                                      handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:actionOne];
    
    UIAlertAction * actionTwo = [UIAlertAction actionWithTitle:NSLocalizedString(@"Login", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"login" bundle:nil];
        LoginViewController *vc = [sb instantiateViewControllerWithIdentifier:@"LoginViewController"];
        [self presentViewController:vc animated:YES completion:nil];
//       VC_INIT_NC_WITH_NIB_NAME_VC_NAME(LeanCloudLoginViewController, loginVC, loginNavi);
//       [self presentViewController:loginNavi animated:YES completion:nil];
    }];
    [alertController addAction:actionTwo];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark alertview delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView != m_addWifiAlertView || buttonIndex == alertView.cancelButtonIndex) {
        return;
    }
    
    UITextField * nameField = [alertView textFieldAtIndex:0];
    UITextField * passwordField = [alertView textFieldAtIndex:1];
    
    if([m_dicLocalWifi objectForKey:nameField.text] != nil){
        ALERT_VIEW(nil, K_NSLOCAL(@"ErrorAlert1"));
        return;
    }
    
    if (nameField.text.length < 1 || passwordField.text.length < 8) {
        ALERT_VIEW(nil, K_NSLOCAL(@"ErrorAlert2"));
        return;
    }
    
    [m_dicLocalWifi setObject:passwordField.text forKey:nameField.text];
    [self flushLocalWifi];
    
    [self.tableView reloadData];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView setEditing:NO animated:YES];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:K_NSLOCAL(@"Alert") message:K_NSLOCAL(@"SureDelete") preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:K_NSLOCAL(@"Cancel") style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:K_NSLOCAL(@"OK") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSArray * keys = [m_dicLocalWifi allKeys];
            NSString * key = [keys objectAtIndex:indexPath.row];
            
            [m_dicLocalWifi removeObjectForKey:key];
            [self flushLocalWifi];
            
            [tableView reloadData];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark local wifi
-(void)loadLocalWifi
{
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    NSDictionary * dicLocalWifi = [ud objectForKey:@"local_wifi"];
    if (dicLocalWifi != nil) {
        m_dicLocalWifi = [[NSMutableDictionary alloc]initWithDictionary:dicLocalWifi];
    }

    if (m_dicLocalWifi == nil) {
        m_dicLocalWifi = [[NSMutableDictionary alloc]init];
    }
    
    if (IS_CHINESE) {
        //在中国区的话把一些假数据加上来
        
        //keys
        NSString * strKeys = @"FBI专线,McDonald-OC,iWuhan-Free,Estelle,M-ivory,yoyo,请输入WiFi名,免费蹭网,cmcc_chinaent,kugou,D-LinkDIR,Tenda_061Dv0,FASTFR48M,HiPER520,Tenda_87y3ge,H3CER8300,卧槽！有wifi！,Tenda_hahaha,Netcore_TTUE,你家WiFi叫啥？,Tenda_tYE24,Linksys_rwu,Tenda_OWVRW,CISCO_twuL,TP-LINK_5Gyehe,TP-LINK_5gey,Kingnet_rqui,MERCURY,TP-LINK_5Gqeo,XIAOMI_IOW,Buffalo_4261,NETGEAR_yqw,搜到爹了吧,HUAWEI_t52,TP-LINK_ywgq,Tenda_61ge2,ZTE_ywe,Link,NETGEAR_541,HUAWEI_tqefgi,CISCO_515,ac66u,R6400,Showfom,TP-LINK_2683,蹭你妹,Take_ytwq,Over_612,网速可慢了,CMCC-4G,CMCC-EDU,Wireless,来自星星的wifi,已欠费,Somnus,Monstar";
        
        NSString * strPasswords = @"zyt25663,81532153oo,nnssbm,gyuewfweo22,671930euf,dhueow,meiyoumima,mfcwu2,ybwi1732,hellokugou,D632930,45678dfghjk,werty367,aer232456,werd5432,qwerty2334,1234gfds,888888888,heyej3132,1.35718E+11,yy1231798,y268137931,5y6yw5ye5,qrqtqq,q44222t3,efragh3,r1326t18231t8,3t712r1hr4,r481g1gu01u,gy431g,6r471g,fvy419pni1,7f8obuipno,1234657i34323,121273y2q,tgwrq3t1,123t52q3gr1,14t1q41g1q3,t52gq52,162763742,12425yt4,24t25gt23,142r1134,1241g5g1,14t1q41t3,1214331611,5314t245414,14r1f1431,8oi586i46,365uhw54,14t3qf4,4t24e15t,135tr2g252,4tqae34,q4tqrg25,5rg64w113";
        
        NSArray * arrayKeys = [strKeys componentsSeparatedByString:@","];
        NSArray * arrayPasswords = [strPasswords componentsSeparatedByString:@","];
        
        if (arrayKeys.count == arrayPasswords.count) {
            for (int i = 0 ; i < arrayKeys.count; i++) {
                [m_dicLocalWifi setObject:[arrayPasswords objectAtIndex:i] forKey:[arrayKeys objectAtIndex:i]];
            }
        }
    }
}

-(void)flushLocalWifi
{
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    
    if (m_dicLocalWifi == nil) {
        m_dicLocalWifi = [[NSMutableDictionary alloc]init];
    }
    
    [ud setObject:m_dicLocalWifi forKey:@"local_wifi"];
}

@end
